/**
 * Copyright (C) 2014 xspace app Project.
 */

package cn.xspace.library.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.cn.wt.wtutils.HttpUtils;
import com.cn.wt.wtutils.http.AsyncCallBack;
import com.cn.wt.wtutils.utils.PackageUtils;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.imcommon.utils.AppUtil;
import com.xspace.android.xafcommon.appliction.BaseApplication;
import com.xspace.android.xafcommon.been.AccountInfo;
import com.xspace.android.xafcommon.been.AppInfoBean;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.DownloadInfo;
import com.xspace.android.xafcommon.db.dbsub.BaseDbMg;
import com.xspace.android.xafcommon.location.LocationInfoBean;
import com.xspace.android.xafcommon.location.LocationResult;
import com.xspace.android.xafcommon.location.MyAMapLocation;
import com.xspace.android.xafcommon.network.exception.HttpException;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.DownloadManager;
import com.xspace.android.xafcommon.util.JSONUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.NotifyManager;
import com.xspace.android.xafcommon.util.PreferencesUtils;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.util.ServiceConstant;
import com.xspace.android.xafcommon.util.StringUtils;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;
import com.xspace.android.xafcommon.view.dialog.SelectDialog;
import com.xspace.android.xafcommon.view.dialog.UpdateDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xspace.library.R;
import cn.xspace.library.bean.PluginBean;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.xspace.android.xafcommon.network.apn.ApnUtil.context;


/**
 * @version V1.0.0
 * @ClassName: Tools
 * @author:qbluo
 * @Date：2014-2-25
 * @Description: TODO
 */
public class Tools {
//    public static String dataBasePath = AppConstant.PATH_DATABASE
//            + BaseApplication.mInstance.getPackageName();

    public interface Action {
        String CALL_PHONE = "拨打电话";
        String SEND_MESSAGE = "发送短信";
        String SEND_EMAIL = "发送邮件";
        String CLIP_NUMBER = "拷贝号码";
        String CLIP_EMAIL = "拷贝地址";
        String CANCEL = "取消";
    }


    /**
     * 点击手机时弹出的对话框
     *
     * @param mode
     */
    public static void showPhoneOrEmailDialog(final Context mContext, final List<String> mode) {
        final String copyContent = mode.get(0);
        final SelectDialog.Builder builder = new SelectDialog.Builder(mContext);
        builder.setSingleChoiceItems(mode, new SelectDialog.ISelectItemListener() {
            @Override
            public void selectItemClick(int position) {
                String action = mode.get(position);
                if (TextUtils.equals(Action.CALL_PHONE, action)) { //拨打电话
                    Tools.getCallByPhone(mContext, copyContent);
                } else if (TextUtils.equals(Action.SEND_MESSAGE, action)) { //发送短信
                    Tools.sendMessageByPhone(mContext, copyContent);
                } else if (TextUtils.equals(Action.SEND_EMAIL, action)) { //发送邮件
                    Tools.sendEmail(mContext, copyContent);
                } else if (TextUtils.equals(Action.CLIP_NUMBER, action)) { //复制手机号
                    ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context
                            .CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText(null, copyContent));
                    T.showShort(mContext, R.string.content_copyed);
                } else if (TextUtils.equals(Action.CLIP_EMAIL, action)) { //复制邮箱
                    ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context
                            .CLIPBOARD_SERVICE);
                    clipboard.setPrimaryClip(ClipData.newPlainText(null, copyContent));
                    T.showShort(mContext, R.string.content_copyed);
                }
            }
        });
        builder.show();
    }

    // 截取html中的img src路径
    public final static List<String> getImgSrc(String imgString) {
        List<String> list = new ArrayList<String>();
        try {
            Pattern patternImgStr = Pattern.compile("<\\s*img\\s*(?:[^>]*)src\\s*=\\s*([^>]+)",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
            Matcher matcher = patternImgStr.matcher(imgString);
            while (matcher.find()) {
                String group = matcher.group(1);
                if (group == null) {
                    continue;
                }
                if (group.startsWith("'")) {
                    list.add(group.substring(1, group.indexOf("'", 1)));
                } else if (group.startsWith("\"")) {
                    list.add(group.substring(1, group.indexOf("\"", 1)));
                } else {
                    list.add(group.split("\\s")[0]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * @param @param  context
     * @param @return
     * @return
     * @throws
     * @Description: MD5加密
     */
    public final static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];

        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }

    /**
     * @param @param  context
     * @param @return
     * @return
     * @throws
     * @Description: 获取当前登陆用户信息
     */
    public final static AccountInfo getCurrentAccountInfo(Context context) {
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.barejid = (String) PreferencesUtils.getPfValue(context, Constants.ACCOUNT_BAREJID_KEY,
                String.class.getName());
        accountInfo.mobile = (String) PreferencesUtils.getPfValue(context, Constants.ACCOUNT_USER_MOBILE,
                String.class.getName());
        accountInfo.uuid = StringUtils.parseName(accountInfo.barejid);
        accountInfo.password = (String) PreferencesUtils.getPfValue(context, Constants.ACCOUNT_PASSWORD_KEY,
                String.class.getName());
        accountInfo.departmentIDByUser = (String) PreferencesUtils.getPfValue(context, Constants.ACCOUNT_USER_DEPTID,
                String.class.getName());
        accountInfo.departmentNameByUser = (String) PreferencesUtils.getPfValue(context,
                Constants.ACCOUNT_USER_DEPTNAME, String.class.getName());
        accountInfo.isAgo = !((String) PreferencesUtils.getPfValue(context, Constants.ACCOUNT_VALIDATED,
                String.class.getName())).equals("1");
        return accountInfo;
    }

    public static void cleanUserInfo(Context context) {
        BuildCache.getAppConfigBean(context).cleanData();
        MyInfoUtil.userInfoBean = null;
        MyInfoUtil.appInfoBean = null;
        MyInfoUtil.appIndexBean = null;
        MyInfoUtil.clearEquipmentMap();
        PreferencesUtils.setPfValue(Constants.ACCOUNT_VALIDATED, "0");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ID, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_PASSWORD_KEY, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_NAME_KEY, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_MOBILE, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_LOGO, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ADDRESS, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_SEX, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_EMAIL, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_DESC, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_BAREJID_KEY, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_AREACODE, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_SCORE, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_DEPTID, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_DEPTNAME, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_DEPTCODE, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ORGTID, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ORGNAME, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ORGCODE, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_QQ, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_DEPT_AREACODE, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ORG_HXID, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ORG_AREACODE, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_QACEXPERT, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_ISFARMER, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_BIZLIST, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_User_Authority_Jsondata, "");

        //退出登录去掉首页数据
        PreferencesUtils.setPfValue(Constants.INDEX_CODE, "");
        PreferencesUtils.setPfValue(Constants.HTML_VERSION, "");
        PreferencesUtils.setPfValue(Constants.OFFLINE_DB, "");
        PreferencesUtils.setPfValue(Constants.SPRING_DB, "");
        PreferencesUtils.setPfValue(Constants.SPRING_DB, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_HUANXIN_FLAG, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_POSTLIST, "");
        PreferencesUtils.setPfValue(Constants.ACCOUNT_USER_RESULT, "");

        PreferencesUtils.setPfValue(Constants.SIGN_SIGNON_TIME, "");
        PreferencesUtils.setPfValue(Constants.SIGN_SIGNOUT_TIME, "");
        PreferencesUtils.setPfValue(Constants.SIGN_TRAIL_INTERVAL, "");
        PreferencesUtils.setPfValue(Constants.JSON_UNDEAL_APPLY_FORM, "");

        PreferencesUtils.setPfValue(Constants.ACCOUNT_REM_PASSWORD_KEY, false + "");
        //每次发起群组是需要判断是否显示过信息.每次登录都要重新显示,所以退出是要把状态还原
        PreferencesUtils.SaveBooleanData("isShowInfo", false);
        //我的待办动物产地检疫申报每次进入时需要弹出提醒框,退出登录后,重置状态
        PreferencesUtils.SaveBooleanData(Constants.ACCOUNT_HAS_SHOW_DECLARE_INFO, false);
    }

    public static boolean isLogin(Activity context) {
        Application app = context.getApplication();
        if (app instanceof BaseApplication) {
            BaseApplication application = (BaseApplication) app;
            return application.isAccountConfigured();
        } else {
            return false;
        }
    }

    /**
     * 给定电话号码拨打电话的方法
     */
    public static void getCallByPhone(Context context, String phone) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel://" + phone));
        context.startActivity(intent);
    }

    /**
     * 给定电话号码发送短信的方法
     *
     * @param context
     */
    public static void sendMessageByPhone(Context context, String phone) {
        Intent share = new Intent();
        share.setAction("android.intent.action.SENDTO")
                .addCategory("android.intent.category.DEFAULT")
                .addCategory("android.intent.category.BROWSABLE")
                .setData(Uri.parse("smsto:" + phone));//smsto会报错
        context.startActivity(share);
    }

    /**
     * 给定电话号码发送短信的方法
     *
     * @param context
     */
    public static void sendEmail(Context context, String email) {
        Intent data = new Intent(Intent.ACTION_SENDTO);
        data.setData(Uri.parse("mailto:" + email));
        context.startActivity(data);
    }

    private static ProgressDialog waitDialog;

    /**
     * 检测新版本的功能
     *
     * @param mContext   上下文
     * @param isMovement 是否是手动检测
     */
    public static void detectionUpdateReq(final Context mContext, final boolean isMovement) {
        //立刻显示对话框.防止点击多次
        waitDialog = DialogHelp.getWaitDialog(mContext, "正在检查新版本");
        waitDialog.setCanceledOnTouchOutside(false);
        if (isMovement) {
            waitDialog.show();
        }
        if (MyAMapLocation.resultLocation != null) {
            sendUpgrade(MyAMapLocation.resultLocation.address, mContext, isMovement);
        } else {
            MyAMapLocation.getInstance().relocation(new LocationResult() {
                @Override
                public void result(boolean flag, LocationInfoBean locationInfoBean) {
                    sendUpgrade(locationInfoBean.address, mContext, isMovement);
                }

                @Override
                public void locationErr(String errMs) {
                    sendUpgrade("", mContext, isMovement);
                }
            });
        }
    }

    public static void detectionPluginUpdate(final Context mContext) {
        //获取检查插件列表信息
        String user_id = MyInfoUtil.getMyUserid(BaseApplication.mInstance);
        final HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", user_id);
        Observable.create(new Observable.OnSubscribe<List<PluginBean>>() {
            @Override
            public void call(Subscriber<? super List<PluginBean>> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.queryApkPlugin, requestMap);
                if (bean != null) {
                    List<PluginBean> beanList = JSONUtil.parseJsonToList(bean.data, new TypeToken<List<PluginBean>>() {
                    }.getType());
                    subscriber.onNext(beanList);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List<PluginBean>>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onNext(List<PluginBean> result) {
                if (result != null && result.size() > 0) {
                    for (PluginBean pluginBean : result) {
                        if (!TextUtils.isEmpty(pluginBean.package_name)) {
                            boolean isInstall = isPackageInstalled(pluginBean.package_name, mContext);
                            if (isInstall) {//是否安装,安装了才检测
                                int appVersion = getAppVersion(pluginBean.package_name, mContext);
                                int newVersion = 0;
                                try {
                                    newVersion = Integer.parseInt(pluginBean.plugin_version_code);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (newVersion > appVersion) { //发现新版本
                                    PreferencesUtils.setPfValue(pluginBean.plugin_name, "1");
//                                    showPlugInUpdateDialog(mContext, pluginBean);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    private static void showPlugInUpdateDialog(final Context mContext, final PluginBean pluginBean) {
        DialogHelp.getConfirmDialogWithoutContent(mContext,
                "发现" + pluginBean.plugin_name + "新版本,是否更新?",
                ResourceUtils.getString(R.string.cancel),
                ResourceUtils.getString(R.string.button_ok), null, new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        AppConstant.ModuleEnum moduleEnum = AppConstant.moduleMap.get(pluginBean.package_name);
                        if (!TextUtils.isEmpty(pluginBean.plugin_path)) {
                            downloadApk(mContext, moduleEnum, pluginBean.plugin_path);
                        }
                    }
                }).show();
    }

    public static String getSimSerialNumber(Context mContext) {
        final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getSimSerialNumber();
    }


    public static String getMODEL() {
        try {
            return android.os.Build.MODEL;
        } catch (Exception e) {
            e.printStackTrace();
            return "型号未获取到";
        }
    }

    public static String getCpuInfo() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String[] cpuInfo = {"", ""};
        String[] arrayOfString;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            for (int i = 2; i < arrayOfString.length; i++) {
                cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
            }
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            cpuInfo[1] += arrayOfString[2];
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cpuInfo[0] + cpuInfo[1];
    }

    public static String getMacAddress(Context mContext) {
        String result = "";
        try {
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            result = wifiInfo.getMacAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getBaseBand() {
        String result = "";
        try {
            Class cl = Class.forName("android.os.SystemProperties");
            Object invoker = cl.newInstance();
            Method m = cl.getMethod("get", new Class[]{String.class, String.class});
            result = (String) m.invoke(invoker, new Object[]{"gsm.version.baseband", "no message"});

        } catch (Exception e) {
        }
        return result;

    }

    public static String getBRAND() {
        try {
            return android.os.Build.BRAND;
        } catch (Exception e) {
            e.printStackTrace();
            return "品牌未获取到";
        }
    }

    /**
     * 发出开始下载的请求
     *
     * @param area       包含的地区信息
     * @param mContext   content
     * @param isMovement 是否是用户手动检测的
     */
    private static void sendUpgrade(String area, final Context mContext, final boolean isMovement) {

        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("uuid", MyInfoUtil.getMyUserid(mContext));
        updateMap.put("department_id", MyInfoUtil.getAppInfo(mContext).app_deptid);
        updateMap.put("mobile", MyInfoUtil.getMyMobile(mContext));
        updateMap.put(RequestConstant.KEY_APP_ID, BuildCache.getAppConfigBean(mContext).appInfo.app_id);
        updateMap.put("imei", getImei(mContext));
        updateMap.put("baseband", getBaseBand());
        updateMap.put("osversion", android.os.Build.VERSION.RELEASE);
        updateMap.put("manufacturer", Tools.getBRAND());
        updateMap.put("mac", getMacAddress(mContext));
        updateMap.put("cpuinfo", getCpuInfo());
        updateMap.put("appversion", BuildCache.getAppConfigBean(mContext).appInfo.app_version);
        updateMap.put("area", area);
        updateMap.put("platform", "0");

        OkHttpManager.getInstance().commonRequestWithoutEncrypt(Constants.URL_APP_UPDATE, updateMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<BaseReturnBean>() {
                    @Override
                    public void call(BaseReturnBean baseReturnBean) {
                        JSONObject jsonVersion = null;
                        try {
                            jsonVersion = new JSONObject(baseReturnBean.data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        jsonVersion = jsonVersion.optJSONObject("app");

                        AppInfoBean appIndex = new AppInfoBean();
                        appIndex.note = jsonVersion.optString("note");
                        appIndex.url = jsonVersion.optString("url");
                        appIndex.app_id = jsonVersion.optString("app_id");
                        appIndex.version = jsonVersion.optString("version");
                        appIndex.app_version = jsonVersion.optString("version");
                        if (!StringUtils.isEmpty(appIndex.app_id)) { //判断appid是否为空
                            //与本地appid判断,不知具体意义,目前是始终不等 TODO,后续了解具体作用再做更改
                            if (!appIndex.app_id.equalsIgnoreCase(BuildCache.getAppConfigBean(mContext).appInfo
                                    .app_id)) {

                                //对比当前版本号和新检测的版本号,确定是否有新版本
//                                Boolean findNew = Double.parseDouble((String) PreferencesUtils.getPfValue(context,
// Constants.ACCOUNT_APP_VERSION, null)) <
//                                        Double.parseDouble(appIndex.version);

                                Boolean findNew = verIdParseNumber(MyInfoUtil.getAppInfo(context).app_version) <
                                        verIdParseNumber(appIndex.version);
                                PreferencesUtils.SaveBooleanData("has_new_version", findNew);//存储是否发现了新版本,用于在个人中中心显示
                                if (findNew) { //发现新版本执行结果
//                                    mCallBack.onResult(appInfoBean);
                                    if (checkCacheVersion(appIndex.version)) {
                                        //如果发现本地保存的版本是最新版本
                                        LogUtil.e("wubaojie>>>" + "本地保存了最新版本");
                                        showUpdateDialog(mContext, appIndex, isMovement, true);
                                        return;
                                    }
                                    dispatchDownloadMode(mContext, appIndex, isMovement);//是wifi模式逻辑在此方法中做,后面不走了

                                } else {
                                    //为最新版
                                    if (isMovement) {
                                        waitDialog.dismiss();
                                        Toast.makeText(mContext, BaseRProxy.msg_update_new_date_over, Toast
                                                .LENGTH_SHORT)
                                                .show();
                                    }
                                }
                            } else {
                                PreferencesUtils.SaveBooleanData("has_new_version", false);
                                if (isMovement) {
                                    waitDialog.dismiss();
                                    Toast.makeText(mContext, BaseRProxy.msg_update_new_date_over, Toast.LENGTH_SHORT)
                                            .show();
                                }
                            }
                        } else { //appid为空,表示服务端没有返回数据,为正常现象,表示没有新版本
                            if (isMovement) {
                                waitDialog.dismiss();
                                Toast.makeText(mContext, BaseRProxy.msg_update_new_date_over, Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }
                    }
                }).subscribe(new Subscriber<BaseReturnBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                LogUtil.d("onError");
//                T.showSingleL(e.getMessage());
                waitDialog.dismiss();
            }

            @Override
            public void onNext(BaseReturnBean baseReturnBean) {
                LogUtil.d("onNext");
                waitDialog.dismiss();
            }
        });

//        new UpgradeImpl(mContext).updateCheck(isMovement, Tools.getCurrentAccountInfo(mContext).uuid,
//                AppCache.getAppConfigBean(mContext).departmentID, AppCache.getAppConfigBean(mContext).appID, area,
//                new UpgradeImpl.IUpdateRequest() {
//                    @Override
//                    //走到这里表示已经发现了新版本了,准备更新
//                    public void onResult(AppInfoBean appInfoBean) {
//                        if (isMovement) {
//                            waitDialog.dismiss();
//                        }
//                        if (checkCacheVersion(appInfoBean.version)) {
//                            //如果发现本地保存的版本是最新版本
//                            LogUtil.e(TAG, "wubaojie>>>" + "本地保存了最新版本");
//                            showUpdateDialog(mContext, appInfoBean, isMovement, true);
//                            return;
//                        }
//                        dispatchDownloadMode(mContext, appInfoBean, isMovement);//是wifi模式逻辑在此方法中做,后面不走了
//                    }
//
//                    @Override
//                    public void onNewest() {
//                        if (isMovement) {
//                            waitDialog.dismiss();
//                        }
//                    }
//
//                    @Override
//                    public void onError() {
//                        if (isMovement) {
//                            waitDialog.dismiss();
//                        }
//                    }
//                });
    }

    public static int verIdParseNumber(String verId) {
        String numStr = verId.replace(".", "");
        if (numStr.length() == 2) {
            numStr += "0";
        }
        return Integer.parseInt(numStr);
    }

    /**
     * 检查是否缓存了该版本
     *
     * @param version
     */
    private static boolean checkCacheVersion(String version) {
        File file = new File(DownloadManager.DOWNLOAD_DIR, File.separator + version + ".apk");
        String cacheVersion = PreferencesUtils.getStringData("cacheApk");
        if (file.exists() && !TextUtils.isEmpty(cacheVersion) && verIdParseNumber(version) == verIdParseNumber
                (cacheVersion)) {//判断本地存在该文件,并且记录的为成功下载完成的状态
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据网络状态判断下载模式
     */
    private static void dispatchDownloadMode(final Context mContext, final AppInfoBean appInfoBean,
                                             final boolean isMovement) {
        boolean isWifi = AppUtil.isConnected(mContext) && AppUtil.getCurrentNetworkType().equals("Wi-Fi");
        if (isWifi) {
            LogUtil.e("wubaojie--", "现在是在WIFI环境下,准备后台下载安装包 url : " + appInfoBean.url);
            if (TextUtils.isEmpty(appInfoBean.url)) {
                LogUtil.e("wubaojie>>>" + "url为空");
                return;
            }
            DownloadManager.getInstance().download(appInfoBean);
            DownloadManager.getInstance().registerDownloadObserver(new DownloadManager.DownloadObserver() {
                @Override
                public void onDownloadStateChange(DownloadInfo downloadInfo) {
                    if (downloadInfo.getState() == DownloadManager.STATE_FINISH) {
                        PreferencesUtils.SaveStringData("cacheApk", downloadInfo.getVersion());
                        showUpdateDialog(mContext, appInfoBean, isMovement, true);
                    }
                }

                @Override
                public void onDownloadProgressChange(DownloadInfo downloadInfo) {

                }
            });
        } else {
            //如果不是wifi模式,则继续
            showUpdateDialog(mContext, appInfoBean, isMovement, false);
        }
    }

    /**
     * 弹出更新的对话框
     *
     * @param appInfoBean 信息对象
     * @param isMovement  是否为用户手动点击的检测
     * @param mContext    上下文
     */
    private static void showUpdateDialog(final Context mContext, final AppInfoBean appInfoBean, boolean isMovement,
                                         final boolean isCache) {
        //获取忽略版本号
        String ignoreVersion = PreferencesUtils.getStringData("ignore_version");
        if (TextUtils.isEmpty(ignoreVersion)) {
            ignoreVersion = "0";
        }
        LogUtil.e("wubaojie-->", "本地记录的忽略的版本" + ignoreVersion);
        LogUtil.e("wubaojie-->", "当前的版本" + appInfoBean.version);
        if (TextUtils.equals(ignoreVersion, appInfoBean.version) && !isMovement) { //当前版本为忽略版本并且不是手动检测的
            //直接返回,不弹出对话框
            return;
        }
        LogUtil.e("wubaojie---", "有新版本,可以更新" + appInfoBean.version);
        if (!StringUtils.isEmpty(appInfoBean.url)) {
            final Boolean isForce = appInfoBean.tag.equals("1");//判断是否是强制更新
            final String version = appInfoBean.version;
            final String newVersionUrl = appInfoBean.url;
            try {
                new UpdateDialog.Builder(mContext)
                        .setForceUpdate(isForce)
                        .setIgnoreGone(isMovement)
                        .setContentMsg(appInfoBean.note)
                        .setConfirmText(isCache ? "安装" : "下载")
                        .isCache(isCache)
                        .setConfirmListener(new ButtonClickListener() {
                            @Override
                            public void buttonClick(View view) {
                                if (isCache) {
                                    DownloadInfo downloadInfo = DownloadInfo.create(appInfoBean);
                                    downloadInfo.setState(DownloadManager.STATE_FINISH);
                                    DownloadManager.getInstance().installApk(appInfoBean);
                                } else {
                                    // TODO 后续更改下载方式
                                    Intent intent = new Intent();
                                    intent.setAction("android.intent.action.VIEW");
                                    Uri app_url = Uri.parse(newVersionUrl);
                                    intent.setData(app_url);
                                    mContext.startActivity(intent);
                                }
                                if (isForce) {// 强制更新
                                    Tools.sendStopServiceBroadcast(mContext);
                                    Tools.sendExitAppBroadcast(mContext);
                                }
                            }
                        })
                        .setIgnoreListener(new ButtonClickListener() {
                            @Override
                            public void buttonClick(View view) {
                                PreferencesUtils.SaveStringData("ignore_version", version);
                                Toast.makeText(mContext, "您仍可以在\"用户中心\"--\"检查新版本\"中获取最新版本", Toast.LENGTH_LONG).show();
                            }
                        })
                        .show();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    /**
     * 根据包名判断apk是否安装
     */
    public static boolean judgeAppInstall(Context context, String packagename) {
        try {
            context.getPackageManager().getPackageInfo(packagename, 0);
            return true;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取APK版本名称(versionName)
     *
     * @param apkPath
     * @return
     */
    private String getVersionName(Context context, String apkPath) {
        PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        String versionName = null;
        if (pi != null) {
            versionName = pi.versionName;
        }
        return versionName;
    }

    /**
     * 获取APK版本号(versionCode)
     *
     * @param apkPath
     * @return
     */
    private int getVersionCode(Context context, String apkPath) {
        PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        int versionCode = 1;
        if (pi != null) {
            versionCode = pi.versionCode;
        }
        return versionCode;
    }

    /**
     * 发送停止服务广播
     */
    public static void sendStopServiceBroadcast(Context context) {
        Intent intent = new Intent(BaseRProxy.BR_SERVICE_HANDLE);
        intent.putExtra(ServiceConstant.BR_SERVICE_HANDLE_KEY, ServiceConstant.BR_SERVICE_HANDLE_STOP_VALUE);
        context.sendBroadcast(intent);
    }

    /**
     * 发送退出程序广播
     */
    public static void sendExitAppBroadcast(Context context) {
        Intent intent = new Intent(BaseRProxy.BR_EXIT_APP);
        //intent.putExtra("key", "stop");
        context.sendBroadcast(intent);
    }

    /**
     * 退出app的做的操作 主要是远程service的关闭 和账号退出和环信的退出
     *
     * @param context
     */
    public static void exitApp(Context context) {
        //退出登录,清楚用户数据
        logoutAndClearData(context);
        //停止服务,退出程序
//        Tools.sendStopServiceBroadcast(context);
//        Tools.sendExitAppBroadcast(context);
    }

    public static void logoutAndClearData(Context context) {
        BaseDbMg.getInstance().getOfflineDataRecordDBBiz().deleteAllRows();
        //关闭数据库
//        BaseDbMg.close();
        NotifyManager.cancelAll(context);
        cleanUserInfo(context);
        //清空Cordova缓存
        clearWebViewCache(context);
        PreferencesUtils.SaveLongData("offlineWorklog", 0);
    }

    public static final String APP_CACAHE_DIRNAME = "/webcache";

    /**
     * 清除WebView缓存
     */
    public static void clearWebViewCache(Context context) {

        //清理Webview缓存数据库
        try {
            context.deleteDatabase("webview.db");
            context.deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebView 缓存文件
        File appCacheDir = new File(context.getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME);
        Log.v("tools", "clearWebViewCache appCacheDir path=" + appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(context.getCacheDir().getAbsolutePath() + "/webviewCache");
        Log.v("tools", "clearWebViewCache webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public static void deleteFile(File file) {

        Log.i("tools", "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e("tools", "delete file no exists " + file.getAbsolutePath());
        }
    }

    public static void CancelServiceAlarm(Context context) {
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent("com.im.XmppConnectCheckBroad");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarm.cancel(pendingIntent);
        //		UserSignInfoService.isRunableRun = false;
        //取消掉定位的广播
        intent = new Intent(BaseRProxy.BR_LOCATION_RECEIVED);
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        alarm.cancel(pendingIntent2);
    }

    /**
     * 方法描述 : 判断service是否在运行
     *
     * @param context
     * @param serviceName
     * @return
     */
    public static boolean isServiceRunnig(Context context, String serviceName) {
        ActivityManager myManager = (ActivityManager) context.getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
                .getRunningServices(Integer.MAX_VALUE);
        for (RunningServiceInfo service : runningService) {
            if (serviceName.equals(service.service.getClassName())) {
                Log.e("tools", "service running true");
                return true;
            }
        }
        Log.e("tools", "service running false");
        return false;
    }

    /**
     * 方法描述 : 从assent文件里面读取图片
     *
     * @param mContext
     * @param fileName
     * @return
     */
    public static Bitmap getImageFromAssetsFile(Context mContext, String fileName) {
        Bitmap image = null;
        AssetManager am = mContext.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    public static boolean isShouldSign() {
        if (BaseApplication.mInstance.isAccountConfigured()) {
            if (!TextUtils.isEmpty(MyInfoUtil.getSignon_time()) //上班时间不为空
                    && !TextUtils.isEmpty(MyInfoUtil.getSignout_time()) //下班时间不为空
                    && !TextUtils.isEmpty(MyInfoUtil.getTrail_interval()) //间隔不为空
                    && !"0".equals(MyInfoUtil.getTrail_interval()) //间隔不为0
                    && MyInfoUtil.isDevicesBind()) { //并且该设备是绑定设备
                long timeOn = Long.parseLong(MyInfoUtil.getSignon_time());
                long timeOut = Long.parseLong(MyInfoUtil.getSignout_time());
                long timeCurrent = Long.parseLong(DateUtils.getCurrentDatetimeString(DateUtils.FORMAT_14));
                if (timeCurrent >= timeOn && timeCurrent <= timeOut) {
                    Log.d("sign", "isShouldSign true");
                    return true;
                }
                if (timeCurrent >= timeOut && timeCurrent <= timeOn) { //晚班
                    Log.d("sign", "isShouldSign true");
                    return true;
                }
            }
        }
        Log.d("sign", "isShouldSign false");
        return false;
    }

    public static String getImei(Context mContext) {
        TelephonyManager manager = (TelephonyManager) mContext.getSystemService(mContext.TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            LogUtil.d("wubaojie>>>getImei: " + manager.getDeviceId());
            Class clazz = manager.getClass();
            try {
                Method getImei = clazz.getDeclaredMethod("getImei", int.class);//(int slotId)
                String imei1 = getImei.invoke(manager, 0).toString();
                LogUtil.d("wubaojie>>>IMEI 1: " + getImei.invoke(manager, 0));
                return imei1;
            } catch (Exception e) {
                e.printStackTrace();
                return manager.getDeviceId();
            }
        } else {
            return manager.getDeviceId();
        }
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static boolean isOpenGPS(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    public static boolean checkModule(final Context mContext, final String packageName) {
        final AppConstant.ModuleEnum moduleEnum = AppConstant.moduleMap.get(packageName);
        if (!Tools.isPackageInstalled(packageName, mContext)) {
            DialogHelp.getConfirmDialogWithoutContent(mContext,
                    "没有安装该模块,是否安装?",
                    ResourceUtils.getString(R.string.cancel),
                    ResourceUtils.getString(R.string.button_ok), null, new ButtonClickListener() {
                        @Override
                        public void buttonClick(View view) {

//                            if (FileUtils.isFileExists(moduleEnum.getApkPath())) {
//                                PackageUtils.installNormal(mContext, moduleEnum.getApkPath());
//                            } else {
                            queryApkPlugin(mContext, moduleEnum);
//                            }
                        }
                    }).show();
            return false;
        } else if ("1".equals(PreferencesUtils.getPfValue(moduleEnum.getKey()))) {
            DialogHelp.getConfirmDialogWithoutContent(mContext,
                    "发现" + moduleEnum.getPlugInName() + "新版本,是否更新?",
                    ResourceUtils.getString(R.string.cancel),
                    ResourceUtils.getString(R.string.button_ok), null, new ButtonClickListener() {
                        @Override
                        public void buttonClick(View view) {
                            queryApkPlugin(mContext, moduleEnum);
                        }
                    }).show();
            return false;
        } else {
            return true;
        }
    }

    public static void queryApkPlugin(final Context mContext, final AppConstant.ModuleEnum anEnum) {
        String user_id = MyInfoUtil.getMyUserid(BaseApplication.mInstance);
        final HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", user_id);
        requestMap.put("plugin_name", anEnum.getKey());
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                BaseReturnBean bean = OkHttpUtils.initHttp(Constants.queryApkPlugin, requestMap);
                if (bean != null) {
                    subscriber.onNext(bean.data);
                } else {
                    subscriber.onError(new HttpException());
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onNext(String result) {
                String plugin_path = JSONUtil.getString(result, "plugin_path", "");
                if (!TextUtils.isEmpty(plugin_path)) {
                    downloadApk(mContext, anEnum, plugin_path);
                }
            }
        });
    }

    public static void downloadApk(final Context mContext, final AppConstant.ModuleEnum anEnum, String plugin_path) {
        HttpUtils httpUtils = new HttpUtils(true);
        httpUtils.download(plugin_path, anEnum.getApkPath(), new
                AsyncCallBack<File>() {
                    @Override
                    public void onStart() {
                        T.showSingleL("正在下载");
                    }

                    @Override
                    public void onLoading(long count, long current) {
                        long div = (current * 100 / count);
                        LogUtil.d("wubaojie>>>onLoading: " + div);
                        // 将进度设置给进度条
                        T.showSingleL(div + "%");
                    }

                    @Override
                    public void onSuccess(File result) {
                        T.showSingleL("下载成功");
                        PackageUtils.installNormal(mContext, anEnum.getApkPath());
                        PreferencesUtils.setPfValue(anEnum.getKey(), "");//清空发现新版本信息
                    }

                    @Override
                    public void onFailure(Throwable error, String msg) {
                        T.showSingleL("下载失败");
                    }
                });
    }

    /**
     * 调用第三方App,获取Intent
     *
     * @param packageName  第三方App程序的包名
     * @param activityName 启动类的全路径名
     * @param bundle
     */
    public static Intent getAppIntent(String packageName, String activityName, Bundle bundle) {
        ComponentName componentName = new ComponentName(packageName, activityName);
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setComponent(componentName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * 判断手机是否安装第三方应用
     */
    public static boolean isPackageInstalled(String pn, Context mContext) {
        PackageManager packageManager = mContext.getPackageManager();
        try {
            PackageInfo pi = packageManager.getPackageInfo(pn, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
            if (null != pi) {
                return true;
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return false;
    }

    /**
     * @param packageName
     * @param context
     * @return
     */
    public static int getAppVersion(String packageName, Context context) {
        int version = 0;
        try {
            PackageInfo appInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            version = appInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }


}
